package cn.mill.spring;

import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;

import cn.mill.spring.annotation.MillScan;

/**
 * 
 * @ClassName MillScannerRegister
 * @Description ServiceDefine 扫描 被 ServiceDefine 注解的类。注册为spring bean。
 * @author nadonghua
 * @date 2019年11月7日 上午11:20:53
 *
 */
public class MillScannerRegister implements ImportBeanDefinitionRegistrar, ResourceLoaderAware {
	
	private ResourceLoader resourceLoader;
	
	@Override
	public void setResourceLoader(ResourceLoader resourceLoader) {
		this.resourceLoader = resourceLoader;
	}
	
	@Override
	public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
		AnnotationAttributes annoAttrs = AnnotationAttributes.fromMap(annotationMetadata.getAnnotationAttributes(MillScan.class.getName()));
		
		String[] basePackages = annoAttrs.getStringArray("value");
		basePackages = basePackages == null ? annoAttrs.getStringArray("basePackage") : basePackages;
		// 没有设置 扫描路径,就扫描对应
		if (basePackages != null && basePackages.length > 0) {
			// 自定义的 包扫描器
			MillClassPathBeanDefinitionScanner scanHandle = new MillClassPathBeanDefinitionScanner(beanDefinitionRegistry, false);
			if (resourceLoader != null) {
				scanHandle.setResourceLoader(resourceLoader);
			}
			scanHandle.setBeanNameGenerator(new MillAnnotationBeanNameGenerator());
			// 扫描指定路径下的接口
			scanHandle.doScan(basePackages);
		}
	}
}
